package edu.vt.ece4564;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class AttendanceActivity extends Activity implements OnClickListener {
    // Debugging
    private static final String TAG = "AttendanceActivity";
    private static final boolean D = true;
    
    // Intent request codes
    private static final int REQUEST_ENABLE_BT = 3;
    
	// Create a BroadcastReceiver for ACTION_FOUND
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        // When discovery finds a device
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	            // Get the BluetoothDevice object from the Intent
	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if(class_.containsKey(device.getAddress())) {
                    	mDevicesArrayAdapter_.add(device.getAddress() + " -- " + device.getName());
                        Log.d("TEST",device.getAddress());
                    	//Log.d("TTEST", dev);
                    	//class_.get(device.getAddress()).present = true;
                    	present_++;
                    	fraction_.setText(present_ + " / " + class_.size());
                    	float temp = (present_ * 100) / class_.size();
                    	Log.d("temp",String.valueOf(temp));
                    	progress_.setProgress((int) temp);
                    }
                    	
                }
                // When discovery is finished, change the Activity title
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    setTitle(R.string.select_devices);
                    if (mDevicesArrayAdapter_.getCount() == 0) {
                        String noDevices = getResources().getText(R.string.no_devices_found).toString();
                        mDevicesArrayAdapter_.add(noDevices);
                }
	        }
	    }
	};
	
	// Instance of a Class
	private HashMap<String,Student> class_ = new HashMap<String,Student>();
	
	// Member Variables
	private int present_;
	
	// Member fields
    private ArrayAdapter<String> mDevicesArrayAdapter_ = null;
	private BluetoothAdapter mBluetoothAdapter_ = null;
	private TextView fraction_ = null;
	private ProgressBar spin_ = null;
	private ProgressBar progress_ = null;
	
	// 
	
	// Member Buttons
	private Button getClass_;
	private Button start_;
	public String jsonString_;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attendance_activity_layout);
		
        // Set result CANCELED in case the user backs out
        setResult(Activity.RESULT_CANCELED);
        
        // Initialize getClass Button
        getClass_ = (Button) findViewById(R.id.getClass);
        getClass_.setOnClickListener(this);
        
        // Initialize Start Button
        start_ = (Button) findViewById(R.id.start);
        start_.setOnClickListener(this);
        
        // Initialize Spin ProgressBar
        spin_ = (ProgressBar) findViewById(R.id.Spinner);
        
        // Initialize progrss ProgressBar
        progress_ = (ProgressBar) findViewById(R.id.progressBar);
        
        // Initialize fraction TextView
        fraction_ = (TextView) findViewById(R.id.fraction);
        
        // Initialize Array Adapter
        mDevicesArrayAdapter_ = new ArrayAdapter<String>(this, R.layout.device_list);
        
        // Initialize ListView for devices
        ListView devicesListView = (ListView) findViewById(R.id.devices);
        devicesListView.setAdapter(mDevicesArrayAdapter_);
        
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    	registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
    	
    	mBluetoothAdapter_ = BluetoothAdapter.getDefaultAdapter();
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if (mBluetoothAdapter_ != null) {
        	mBluetoothAdapter_.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }
	
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter_.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        }
    }
    
	@Override
	public void onClick(View v) {
		switch(v.getId()) {
			case R.id.getClass:
				
				fraction_.setVisibility(View.VISIBLE);
				class_.clear();
	        	String ClassID = "1";
	        	asyncRequest askForDB = new asyncRequest("http://172.31.137.49:8080/getBluetoothMapping?", ClassID, AttendanceActivity.this);
	            askForDB.execute();		//start the http request thread 
				break;
			case R.id.start:
				if(start_.getText() == getText(R.string.start)){
					spin_.setVisibility(View.VISIBLE);
					start_.setText(R.string.stop);
					
			        // If we're already discovering, stop it
			        if (mBluetoothAdapter_.isDiscovering()) {
			            mBluetoothAdapter_.cancelDiscovery();
			        }
			        
			        present_ = 0;
			        fraction_.setText(present_ + " / " + class_.size());
			        mDevicesArrayAdapter_.clear();
			       
			        mBluetoothAdapter_.startDiscovery();
					
				} else {
					spin_.setVisibility(View.INVISIBLE);
					start_.setText(R.string.start);
					
			        // If we're already discovering, stop it
			        if (mBluetoothAdapter_.isDiscovering()) {
			            mBluetoothAdapter_.cancelDiscovery();
			        }
				}
				break;
			default:
				break;
		}
	}
	
	 public void parseJson(String jString){
	    	try {
				JSONObject json = (JSONObject) new JSONParser().parse(jString);
				Set m = json.keySet();
				long num  = (Long) json.get("NumberOfStudents");

				List<String> l = new ArrayList<String>();
				
				for (long i=0; i< num; i++){
					l.add(json.get("StudentID" + i).toString());
					Log.e("StudentList", json.get("StudentID" + i).toString());
					
				}
				
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
	    	
	    }

	public void parseToMap(String jString) {
		JSONObject json;
		try {
			json = (JSONObject) new JSONParser().parse(jString);
			Set m = json.keySet();
		//long num  = (Long) json.get("NumberOfStudents");
		
			for (Object s_ : m){
				
				Student temp = new Student();
				
				temp.name_ = (String) json.get(s_.toString());
		
				class_.put(s_.toString(), temp);
				Log.d("MORON",s_.toString());
				
				fraction_.setText("0 / " + class_.size());
				//.add(json.get("StudentID" + i).toString());
				//Log.e("StudentList", json.get("StudentID" + i).toString());
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}
}
